<?php

//js для редактирования формы
$this->headScript()->appendFile("/js/admin/form.js");

//html-editor
$this->headScript()->appendFile('/editor/tiny_mce/tiny_mce.js', 'text/javascript');

$this->jQuery()->addOnLoad('
	$("button").live("mouseout", function() {
		$(this).removeClass("ui-state-focus ui-state-active").addClass("ui-state-default");
		return false;
	});
');

$this->headScript('SCRIPT', '
    tinyMCE.init({
        language: "en",
        mode : "specific_textareas",
        editor_selector : "mce_editor",
        theme : "advanced",
        theme_advanced_buttons1 : "emotions,mylistbox,mysplitbutton,bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left"
    });
');
?>

<script type="text/javascript">

$(document).ready(function() {
    var blocks = <?= Zend_Json::encode($this->dynamicContentBlocks) ?>;
    var formId = "<?= $this->form->getId() ?>";
    var jqForm = $("#" + formId);
    var selector = "fieldset[rel=content_block]";
    var len = jqForm.find(selector).length;
    var constr = new $.formConstructor({fieldsetIndex: len, formId: formId});
    var selectedFieldset = null;
	var dialogBoxId = "content_dialog";
    var mceConfig = {
        language: "en",
        mode : "specific_textareas",
        editor_selector : "mce_editor",
        theme : "advanced",
        theme_advanced_buttons1 : "emotions,mylistbox,mysplitbutton,bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left"
    };

    function changePosition(bt, direction) {
        var sibling;
        var fieldset = $(bt).parents(selector);

        if (direction > 0) {
            sibling = fieldset.prevAll(selector).first();
        } else {
            sibling = fieldset.nextAll(selector).first();
        }

        if (sibling.length > 0) {
            var element = $("#order-" + sibling.attr("id"));
            var order = element.val();

            var curElement = $("#order-" + fieldset.attr("id"));
            var curOrder = curElement.val();

            var fieldsetDialog = fieldset.nextAll().first();
            var siblingDialog = sibling.nextAll().first();

            element.val(curOrder);
            curElement.val(order);

            if (direction > 0) {
                fieldset.insertBefore(sibling);
            } else {
                fieldset.insertAfter(sibling);
            }

            if (fieldsetDialog.length > 0) {
               fieldsetDialog.insertAfter(fieldset);
            }

            if (siblingDialog.length > 0) {
                siblingDialog.insertAfter(sibling);
            }

            changeButtonStatus();
        }
    }

    function initPositionButton(i, bt) {
        var icon;
        var direction;

		switch (bt.className) {
			case "up":
				icon = "ui-icon-arrow-1-n";
                direction = 1;
			break;

			case "down":
				icon = "ui-icon-arrow-1-s";
                direction = -1;
			break;
		}

		$(bt).button({
			icons: {
				primary: icon
			}
		}).click(function() {
            changePosition(this, direction);
        });
    }

    function initDialogButton(i, bt) {
         $(bt).button({
            icons: {
                primary: "ui-icon-plus"
            }
        }).click(openDialog);
    }

    function openDialog() {
        var fieldset = $(this).parent().prev(selector);
        if (fieldset.length > 0) {
            selectedFieldset = fieldset;
        }

        $("#" + dialogBoxId).dialog("open");
    }

    function setOrder(element, order) {
        var id = $(element).attr("id");
        var value = $("#order-" + id).val();

        if (!value) {
            value = order;
        } else {
            value = parseInt(value);
        }

        $("#order-" + id).val(value + order);
    }

    function deleteFieldset() {
        if (confirm("Удалить блок?")) {
            var fieldset = $(this).parents(selector);

            fieldset.nextAll(selector).each(function() {
                setOrder(this, -1);
            });

            fieldset.next().find(".dialog_button").parent().remove();
            fieldset.remove();

            //constr.decrFieldsetIndex();

            changeButtonStatus();
        }
    }

    function changeButtonStatus() {
        var collection = jqForm.find(selector);

        if (collection.length == 1) {
            collection.find("button").button("option", "disabled", true);
        } else {
            collection.find("button").button("option", "disabled", false);

            collection.first().find("button.up").button("option", "disabled", true);
	        collection.last().find("button.down").button("option", "disabled", true);
        }
    }

    function overlayMceTextarea( textareaNode ) {
    	var obj = $(textareaNode);
    	var mce = obj.parent().find('.mceEditor');
		var parent = obj.parent();

		obj.css({'margin-bottom': '0', 'border-bottom-width': '1px'});

        var overlay = $('<div style="float:left;overflow:hidden;zoom:1;"></div>');
        overlay.append(obj).append(mce);
        parent.append(overlay);

		var editorId = obj.attr('id').replace(/[\[\]]/g, '_');

    	var toggler = $('<div><input type="checkbox" id="'+editorId+'_mce" class="mceToggler" /><label for="'+editorId+'_mce">Режим HTML</label></div>');
    	toggler.width(overlay.width()).css('text-align', 'right');

    	var checkbox = toggler.find(':input');
    	checkbox.button();
    	checkbox.data('textarea', obj.attr('id'));

		toggler.find('[for="'+editorId+'_mce"]').removeClass('ui-corner-all').addClass('ui-corner-bottom').css({'border-top': 'none', 'margin-right': '0'});
		overlay.append(toggler);
    }

    $("#" + dialogBoxId).dialog({
        autoOpen: false,
        height: 120,
        width: 612,
        modal: false
    });

    jqForm.find(".dialog_button").each(initDialogButton);

    $("#bt_select_block").click(function() {
        var index = $("#select_block").val();

        if (undefined !== blocks[index]) {

            var container, orderElement, order = 0;

            if (selectedFieldset) {
                container = selectedFieldset;
            } else {
                container = $("#" + formId).find(selector + ":first");
            }

            orderElement = $("#order-" + container.attr("id"));
            if (orderElement.length > 0) {
                order = orderElement.val();
            }

            var buttonsGroup = constr.createButtonsGroup({class: "content_right", separator: "&nbsp;"},
                [
                    {type: "button", label: "вверх", class: "up"},
                    {type: "button", label: "вниз", class: "down"}
                ]
            );

            var html = constr.createFieldset(blocks[index], null, {
                order: order,
                prependHtml: '<span class="width2 height2 content_right" rel="delete"></span>',
                appendHtml: buttonsGroup
            });

            var fieldset = $(html);

            fieldset.find("span[rel=delete]").button({
                icons: {
                    primary: "ui-icon-close"
                },
                text: false

            }).click(deleteFieldset);

            fieldset.insertAfter(container).find("button").each(initPositionButton);

            var dlgButtonBlock = jqForm.find(".dialog_button:first").parent().clone();

            dlgButtonBlock.insertAfter(container);
            dlgButtonBlock.find("button").click(openDialog);

            container.nextAll(selector).each(function() {
                setOrder(this, 1);
            });

            changeButtonStatus();

            fieldset.find("textarea.mce_editor").each(function() {
				var obj = $(this);
                var editorId = obj.attr('name');
                obj.attr('id', editorId);
                overlayMceTextarea(this);

                var mceInstance = new tinymce.Editor(editorId, mceConfig);
                mceInstance.render();
            });

            $("#" + dialogBoxId).dialog("close");
        }

        return false;
    });

    jqForm.find(selector).find("button").each(initPositionButton);

    changeButtonStatus();

    jqForm.find("span[rel=delete]").button({
        icons: {
            primary: "ui-icon-close"
        },
        text: false

    }).click(deleteFieldset);

    $('textarea.mce_editor').each(function(){
    	overlayMceTextarea(this);
    });

    $('.mceToggler').live('change', function(){
		if ($(this)[0].checked) {
			tinyMCE.execCommand('mceRemoveControl', false, $(this).data('textarea'));
		} else {
			tinyMCE.execCommand('mceAddControl', false, $(this).data('textarea'));
		}
   	});

});

</script>

<div class="form" id="page_form">
    <form class="zend_form" action="<?= $this->form->getAction() ?>" id="<?= $this->form->getId() ?>" method="<?= $this->form->getMethod() ?>" enctype="<?= $this->form->getEnctype() ?>">

        <? foreach ($this->content as $content) : ?>
            <?= $content ?>
        <? endforeach ?>

        <?= $this->form->getDisplayGroup('default') ?>

        <? if ($this->hasDynamicContent) : ?>

        <div class="ma2" id="content_dialog" title="Вставить новый блок" style="display:none">
            <table cellpadding="0" cellspacing="0" border="0" class="table1">
                <tr style="vertical-align:middle">
                    <td><label for="select_block">Выберите тип блока:</label></td>
                    <td>
                        <select id="select_block">
                        <? foreach ($this->dynamicContentBlocks as $key => $block) : ?>

                        <option value="<?= $key ?>"><?= $block['legend'] ?></option>

                        <? endforeach ?>
                    </select>
                    </td>
                    <td>
                       <?= $this->JQueryButton('bt_select_block', null, null, array('title' => 'Вставить')) ?>
                    </td>
                </tr>
            </table>
        </div>
        <? endif ?>

        <? if ($this->staticContentBlocks) : ?>
            <? foreach ($this->staticContentBlocks as $index => $block) : ?>

                <fieldset rel="content_block" id="<?= $block['id'] ?>">
                    <? if ($block['multiple']) : ?>

                    <span class="width2 height2 content_right" rel="delete"></span>

                    <? endif ?>

                    <legend><?= $block['legend'] ?></legend>
                    <dl>
                    <? foreach ($block['items'] as $key => $element) : ?>
                        <dt><label for="<?= $element['name'] ?>"><?= $element['label'] ?></label> </dt>
                        <dd>
                            <?= $block['html_elements'][$key] ?>
                            <? if ($element['type'] == 'image') : ?>
                                <br />
                                <img src="<?= $element['value']['shortpath'] ?>" alt="" />
                            <? endif ?>
                        </dd>
                    <? endforeach ?>
                    </dl>

                    <?= $block['html_elements']['order'] ?>

					<div class="content_right">
						<button class="up" type="button">вверх</button>&nbsp;<button class="down" type="button">вниз</button>
					</div>

                </fieldset>

                <? if ($this->hasDynamicContent) : ?>

                <div class="ma2" style="text-align:right">
                    <button class="dialog_button" type="button">Вставить блок</button>
                </div>

                <? endif ?>

            <? endforeach ?>
        <? endif ?>

            <?= $this->form->getElement('save') ?>
            <?= $this->form->getElement('qsave') ?>

    </form>

    <br/>
</div>